package com.fzy.core.acegi;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.Element;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.springframework.dao.DataRetrievalFailureException;

public class ResourceCache {

	protected final Logger log = Logger.getLogger(getClass());

	private Cache cache;

	public void setCache(Cache cache) {
		this.cache = cache;
	}

	public Cache getCache() {
		return this.cache;
	}

	public Resource getAuthorityFromCache(String resourceString) {
		Element element = null;

		try {
			element = cache.get(resourceString);
		} catch (CacheException cacheException) {
			throw new DataRetrievalFailureException("Cache failure: "
					+ cacheException.getMessage(), cacheException);
		}

		if (log.isDebugEnabled()) {
			log.debug("Cache hit: " + (element != null) + "; resString: "
					+ resourceString);
		}

		if (element == null) {
			return null;
		} else {
			return (Resource) element.getValue();
		}
	}

	public void putAuthorityInCache(Resource resource) {
		Element element = new Element(resource.getResourceString(),
				resource);
		if (log.isDebugEnabled()) {
			log.debug("Cache put: " + element.getKey());
		}
		this.cache.put(element);
	}

	public void removeAuthorityFromCache(String resourceString) {
		if (log.isDebugEnabled()) {
			log.debug("Cache remove: " + resourceString);
		}
		this.cache.remove(resourceString);
	}

	public List getResources() {
		List resources;
		List resourceList = new ArrayList();
		try {
			resources = this.cache.getKeys();
		} catch (IllegalStateException e) {
			throw new IllegalStateException(e.getMessage());
		} catch (CacheException e) {
			throw new UnsupportedOperationException(e.getMessage());
		}
		for (Iterator iter = resources.iterator(); iter.hasNext();) {
			String resString = (String) iter.next();
			resourceList.add(resString);
		}
		return resourceList;
	}

}
